

#include "WkQueue.h"

WkQueue::WkQueue(PlayerStatus * playerStatus)
{
   this->playerStatus = playerStatus ;
    //对象锁
    pthread_mutex_init(&mutexPacket ,NULL) ;
    // 信号锁
    pthread_cond_init(&condPacket ,NULL) ;
}

WkQueue::~WkQueue()
{
    clearAvPacket();
}

int WkQueue::putAvPacket(AVPacket *avPacket)
{
    pthread_mutex_lock(&mutexPacket) ;
    queuePacket.push(avPacket) ;
    // 通知因缺少资源而休眠的线程醒来
    pthread_cond_signal(&condPacket) ;
    pthread_mutex_unlock(&mutexPacket) ;
    return 0;
}

int WkQueue::getAvPacket(AVPacket *avPacket)
{
    pthread_mutex_lock(&mutexPacket) ;
    while(playerStatus!=NULL &&  !playerStatus->exit)
    {
        if(queuePacket.size() >0)
        {
            AVPacket * packet = queuePacket.front();
            if(av_packet_ref(avPacket ,packet)==0)
            {
                queuePacket.pop();
            }

            av_packet_free(&packet) ;
            av_free(packet) ;
            packet=NULL ;
            break ;
        }else{
            // 等待
            pthread_cond_wait(&condPacket ,&mutexPacket) ;
        }
    }
    pthread_mutex_unlock(&mutexPacket) ;
    return 0;
}

int WkQueue::getQueueSize()
{
    int size = 0 ;
    pthread_mutex_lock(&mutexPacket) ;
    size = queuePacket.size() ;
    pthread_mutex_unlock(&mutexPacket) ;
    return size;
}

void WkQueue::clearAvPacket()
{
    pthread_cond_signal(&condPacket) ;
    pthread_mutex_lock(&mutexPacket) ;

    while(!queuePacket.empty())
    {
        AVPacket *packet = queuePacket.front();
        queuePacket.pop();
        av_packet_free(&packet) ;
        av_free(packet) ;
        packet =NULL ;
    }
    pthread_mutex_unlock(&mutexPacket);
}


